<template>
  <div 
    :class="[
      'bx-date-picker',
      'bx-glass',
      {
        'bx-date-picker--disabled': disabled,
        'bx-date-picker--focused': showPanel
      }
    ]"
    v-click-outside="handleClickOutside"
  >
    <BxInput
      :model-value="displayValue"
      :placeholder="placeholder"
      :disabled="disabled"
      :readonly="readonly"
      :size="size"
      @focus="handleFocus"
      @blur="handleBlur"
      @click="togglePanel"
      class="bx-date-picker__input"
    >
      <template #suffix>
        <BxIcon name="calendar" class="bx-date-picker__icon" />
        <BxIcon 
          v-if="clearable && displayValue"
          name="x-circle"
          class="bx-date-picker__clear"
          @click.stop="handleClear"
        />
      </template>
    </BxInput>

    <div 
      v-if="showPanel"
      class="bx-date-picker__panel bx-glass"
    >
      <div class="bx-date-picker__header">
        <BxButton 
          variant="text" 
          size="small" 
          @click="prevYear"
        >
          <BxIcon name="double-chevron-left" />
        </BxButton>
        <BxButton 
          variant="text" 
          size="small" 
          @click="prevMonth"
        >
          <BxIcon name="chevron-left" />
        </BxButton>
        <span class="bx-date-picker__header-text">
          {{ currentYear }}年 {{ currentMonth + 1 }}月
        </span>
        <BxButton 
          variant="text" 
          size="small" 
          @click="nextMonth"
        >
          <BxIcon name="chevron-right" />
        </BxButton>
        <BxButton 
          variant="text" 
          size="small" 
          @click="nextYear"
        >
          <BxIcon name="double-chevron-right" />
        </BxButton>
      </div>
      
      <div class="bx-date-picker__weekdays">
        <span v-for="day in weekdays" :key="day">{{ day }}</span>
      </div>
      
      <div class="bx-date-picker__days">
        <span 
          v-for="(day, index) in daysInMonth"
          :key="index"
          :class="[
            'bx-date-picker__day',
            {
              'bx-date-picker__day--prev-month': day.type === 'prev',
              'bx-date-picker__day--next-month': day.type === 'next',
              'bx-date-picker__day--current-month': day.type === 'current',
              'bx-date-picker__day--selected': isSelected(day),
              'bx-date-picker__day--today': isToday(day),
              'bx-date-picker__day--disabled': day.disabled
            }
          ]"
          @click="handleDayClick(day)"
        >
          {{ day.date.getDate() }}
        </span>
      </div>
      
      <div class="bx-date-picker__footer">
        <BxButton variant="text" size="small" @click="selectToday">今天</BxButton>
        <BxButton type="primary" size="small" @click="confirmSelection">确定</BxButton>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import BxInput from '../input/BxInput.vue'
import BxIcon from '../basic/BxIcon.vue'
import BxButton from '../basic/BxButton.vue'

export default {
  name: 'BxDatePicker',
  components: {
    BxInput,
    BxIcon,
    BxButton
  },
  props: {
    modelValue: {
      type: [Date, String],
      default: null
    },
    placeholder: {
      type: String,
      default: '请选择日期'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'medium',
      validator: (value) => ['small', 'medium', 'large'].includes(value)
    },
    format: {
      type: String,
      default: 'YYYY-MM-DD'
    },
    disabledDate: {
      type: Function,
      default: () => false
    }
  },
  emits: ['update:modelValue', 'change', 'focus', 'blur'],
  directives: {
    clickOutside: {
      mounted(el, binding) {
        el.__clickOutsideHandler__ = (event) => {
          if (!(el === event.target || el.contains(event.target))) {
            binding.value(event)
          }
        }
        document.addEventListener('click', el.__clickOutsideHandler__)
      },
      unmounted(el) {
        document.removeEventListener('click', el.__clickOutsideHandler__)
      }
    }
  },
  setup(props, { emit }) {
    const showPanel = ref(false)
    const selectedDate = ref(props.modelValue ? new Date(props.modelValue) : null)
    const panelDate = ref(selectedDate.value || new Date()) // 用于面板显示的日期

    const currentYear = computed(() => panelDate.value.getFullYear())
    const currentMonth = computed(() => panelDate.value.getMonth())

    const weekdays = ['日', '一', '二', '三', '四', '五', '六']

    const displayValue = computed(() => {
      if (!selectedDate.value) return ''
      const year = selectedDate.value.getFullYear()
      const month = String(selectedDate.value.getMonth() + 1).padStart(2, '0')
      const day = String(selectedDate.value.getDate()).padStart(2, '0')
      
      let formatted = props.format
      formatted = formatted.replace(/YYYY/g, year)
      formatted = formatted.replace(/MM/g, month)
      formatted = formatted.replace(/DD/g, day)
      return formatted
    })

    const daysInMonth = computed(() => {
      const days = []
      const year = currentYear.value
      const month = currentMonth.value

      // 上个月的最后一天
      const prevMonthLastDay = new Date(year, month, 0).getDate()
      // 当前月的第一天是星期几
      const currentMonthFirstDayWeek = new Date(year, month, 1).getDay()
      // 当前月的总天数
      const currentMonthDays = new Date(year, month + 1, 0).getDate()

      // 填充上个月的日期
      for (let i = 0; i < currentMonthFirstDayWeek; i++) {
        const date = new Date(year, month - 1, prevMonthLastDay - currentMonthFirstDayWeek + 1 + i)
        days.push({ date, type: 'prev', disabled: props.disabledDate(date) })
      }

      // 填充当前月的日期
      for (let i = 1; i <= currentMonthDays; i++) {
        const date = new Date(year, month, i)
        days.push({ date, type: 'current', disabled: props.disabledDate(date) })
      }

      // 填充下个月的日期
      const remainingDays = 42 - days.length // 6行7列共42个格子
      for (let i = 1; i <= remainingDays; i++) {
        const date = new Date(year, month + 1, i)
        days.push({ date, type: 'next', disabled: props.disabledDate(date) })
      }
      return days
    })

    const togglePanel = () => {
      if (props.disabled) return
      showPanel.value = !showPanel.value
      if (showPanel.value) {
        panelDate.value = selectedDate.value || new Date()
      }
    }

    const handleClickOutside = () => {
      showPanel.value = false
    }

    const handleFocus = (event) => {
      emit('focus', event)
    }

    const handleBlur = (event) => {
      emit('blur', event)
    }

    const prevMonth = () => {
      panelDate.value = new Date(currentYear.value, currentMonth.value - 1, 1)
    }

    const nextMonth = () => {
      panelDate.value = new Date(currentYear.value, currentMonth.value + 1, 1)
    }

    const prevYear = () => {
      panelDate.value = new Date(currentYear.value - 1, currentMonth.value, 1)
    }

    const nextYear = () => {
      panelDate.value = new Date(currentYear.value + 1, currentMonth.value, 1)
    }

    const handleDayClick = (day) => {
      if (day.disabled) return
      selectedDate.value = day.date
      panelDate.value = day.date // 同步面板日期
      // emit('update:modelValue', selectedDate.value)
      // emit('change', selectedDate.value)
      // showPanel.value = false
    }

    const isSelected = (day) => {
      if (!selectedDate.value) return false
      return day.date.toDateString() === selectedDate.value.toDateString()
    }

    const isToday = (day) => {
      const today = new Date()
      return day.date.toDateString() === today.toDateString()
    }

    const handleClear = () => {
      selectedDate.value = null
      emit('update:modelValue', null)
      emit('change', null)
    }

    const selectToday = () => {
      selectedDate.value = new Date()
      panelDate.value = new Date()
      // emit('update:modelValue', selectedDate.value)
      // emit('change', selectedDate.value)
      // showPanel.value = false
    }

    const confirmSelection = () => {
      emit('update:modelValue', selectedDate.value)
      emit('change', selectedDate.value)
      showPanel.value = false
    }

    watch(() => props.modelValue, (newVal) => {
      selectedDate.value = newVal ? new Date(newVal) : null
      if (!showPanel.value) {
        panelDate.value = selectedDate.value || new Date()
      }
    })

    return {
      showPanel,
      selectedDate,
      currentYear,
      currentMonth,
      weekdays,
      daysInMonth,
      displayValue,
      togglePanel,
      handleClickOutside,
      handleFocus,
      handleBlur,
      prevMonth,
      nextMonth,
      prevYear,
      nextYear,
      handleDayClick,
      isSelected,
      isToday,
      handleClear,
      selectToday,
      confirmSelection
    }
  }
}
</script>

<style scoped>
.bx-date-picker {
  position: relative;
  display: inline-block;
  font-family: var(--bx-font-family);
}

.bx-date-picker__input {
  cursor: pointer;
}

.bx-date-picker__icon {
  font-size: 16px;
  color: var(--bx-text-secondary);
}

.bx-date-picker__clear {
  font-size: 14px;
  color: var(--bx-text-tertiary);
  cursor: pointer;
  margin-left: 8px;
}

.bx-date-picker__clear:hover {
  color: var(--bx-text-primary);
}

.bx-date-picker__panel {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  width: 280px;
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-medium);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  animation: bx-fade-in-up 0.2s ease-out;
  padding: 16px;
}

.bx-date-picker__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.bx-date-picker__header-text {
  font-size: 16px;
  font-weight: 600;
  color: var(--bx-text-primary);
}

.bx-date-picker__weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-size: 12px;
  color: var(--bx-text-secondary);
  margin-bottom: 8px;
}

.bx-date-picker__days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.bx-date-picker__day {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  cursor: pointer;
  transition: all var(--bx-transition-fast);
  font-size: 14px;
  color: var(--bx-text-primary);
}

.bx-date-picker__day:hover {
  background: var(--bx-glass-bg-hover);
}

.bx-date-picker__day--prev-month,
.bx-date-picker__day--next-month {
  color: var(--bx-text-tertiary);
}

.bx-date-picker__day--selected {
  background: rgba(0, 122, 255, 0.8);
  color: #fff;
}

.bx-date-picker__day--selected:hover {
  background: rgba(0, 122, 255, 0.9);
}

.bx-date-picker__day--today {
  border: 1px solid rgba(0, 122, 255, 0.5);
}

.bx-date-picker__day--disabled {
  opacity: 0.4;
  cursor: not-allowed;
  background: transparent !important;
  color: var(--bx-text-tertiary) !important;
}

.bx-date-picker__footer {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
  border-top: 1px solid var(--bx-glass-border);
  padding-top: 12px;
}

@keyframes bx-fade-in-up {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bx-date-picker {
    width: 100%;
  }
  
  .bx-date-picker__panel {
    width: 100%;
    left: 0;
    right: 0;
  }
}
</style>

